<?php
require 'db.php'; // 包含数据库连接
require 'vendor/autoload.php'; // 引入 Composer 自动加载器
include_once 'secret/jwt.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

if (!isset($_COOKIE['token'])) {
    header('Location: index.php');
    exit();
}

$jwt = $_COOKIE['token'];

try {
    $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));
    $username = $decoded->data->username;
    $user_id = $decoded->data->id;
} catch (Exception $e) {
    echo json_encode([
        'error' => '访问被拒绝: ' . $e->getMessage()
    ]);
    exit();
}

$query = "
    SELECT a.id, a.title, u.username AS author, a.created_at
    FROM articles a
    JOIN favorites f ON a.id = f.article_id
    JOIN users u ON a.author = u.id
    WHERE f.user_id = ?
";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$favorites = [];
while ($row = $result->fetch_assoc()) {
    $favorites[] = $row;
}

echo json_encode(['favorites' => $favorites]);
?>
